package com.hrt.datasender.datadao.service;

import java.text.SimpleDateFormat;
import java.util.Date;

import com.btcode.db.conver.DefaultValueConver;
import com.btcode.db.conver.IValueConver;
import com.btcode.db.executer.IDataExecuter;
import com.btcode.db.sqlparameter.SQLParameterList;
import com.btcode.orm.executer.IORMExecuter;
import com.hrt.datasender.datadao.model.BdSourceReadRecordModel;
import com.hrt.datasender.datastorage.StorageDataType;
import com.hrt.db.DBManager;

public final class BdSourceReadRecordService {

    private static volatile BdSourceReadRecordService instance;

    private BdSourceReadRecordService() {

    }

    public static BdSourceReadRecordService getInstance() {
        if (instance == null) {
            synchronized (BcDeviceService.class) {
                if (instance == null) {
                    instance = new BdSourceReadRecordService();
                }
            }
        }
        return instance;
    }

    /**
     * 初始化读取记录
     * 
     * @param strategyId
     * @param dataType
     */
    public void initReadRecord(String strategyId, StorageDataType dataType) {

        IORMExecuter ormExecuter = DBManager.getORMExecuter();

        BdSourceReadRecordModel bdr = new BdSourceReadRecordModel();
        bdr.setId(strategyId);
        bdr.setProtocolId(strategyId);
        bdr.setDataType(dataType.toString());
        bdr.setLastReadTime(new Date());
        ormExecuter.create(bdr);
    }

    /**
     * 初始化读取记录
     * 
     * @param strategyId
     * @param dataType
     */
    public void updateReadRecord(String strategyId, Date readTime) {

        SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        IORMExecuter ormExecuter = DBManager.getORMExecuter();

        BdSourceReadRecordModel bdr = new BdSourceReadRecordModel();
        bdr.setId(strategyId);
        bdr.setLastReadTime(readTime);
        bdr.setLastReadTimeText(sf.format(readTime));
        ormExecuter.update(bdr);
    }

    /**
     * 根据策略获取最后读取时间
     * 
     * @param strategyId
     * @return
     */
    public Date getLastReadTime(String strategyId) {
        IDataExecuter sqlletExecuter = DBManager.getDataExecuter();

        String sql = "select * from BD_SOURCE_READ_RECORD where PROTOCOL_ID=@id ";
        SQLParameterList pc = new SQLParameterList();
        pc.put("id", strategyId);

        Object value = sqlletExecuter.queryScalar(sql, pc);

        IValueConver valueConver = new DefaultValueConver();
        Date result = valueConver.converToDate(value);

        return result;
    }

}
